    package com.douyu.water.core.web.controller;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.douyu.water.core.Configure;
import com.douyu.water.core.PagePara;
import com.douyu.water.core.model.Area;
import com.douyu.water.core.model.Data;
import com.douyu.water.core.model.Rtu;
import com.douyu.water.core.model.User;
import com.douyu.water.core.model.WtldData;
import com.douyu.water.core.model.WtldRtu;
import com.douyu.water.core.model.WtldSzyData;
import com.douyu.water.core.model.WtldSzyRtu;
import com.douyu.water.core.model.ZKData;
import com.douyu.water.core.model.ZKRtu;
import com.douyu.water.core.service.DataService;
import com.douyu.water.core.service.EquiService;
import com.douyu.water.util.CreateExcelPoi;
import com.douyu.water.util.ParseXmlFile;
import com.douyu.water.util.XmlConfig;

@Controller
@RequestMapping("/data/*")
public class DataController {

	@Resource
	private DataService dataService;
	@Resource
	private EquiService equiService;
	/**
	 * 检索Data表中数据
	 * @param request
	 * @param record
	 * @param page
	 * @return
	 */
	@RequestMapping("/selectData")
	public String selectData(HttpServletRequest request,Data record,PagePara page)
	{
		String result = "WEB-INF/jsp/data/list";
		try
		{
			String fac=request.getParameter("factory");
			int factory=0;
			if(fac!=null){
				factory=Integer.parseInt(fac);
			}
			List<Data> list = dataService.select(record, page,factory);
			request.setAttribute("list", list);
			request.setAttribute("factory", factory);
			request.setAttribute("pagePara",page);
			request.setAttribute("flag", (String)(request.getParameter("flag")));
			request.setAttribute("stationnumber", record.getStationnumber());
			request.setAttribute("datetime", record.getDatetime());
			request.setAttribute("datetimeend", record.getDatetimeend());
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 检索tblCAIJISHUJU表中数据
	 * @param request
	 * @param record
	 * @param page
	 * @return
	 */
	@RequestMapping("/selectZKData")
	public String selectZKData(HttpServletRequest request,ZKData record,PagePara page)
	{
		String result = "WEB-INF/jsp/shuizhi/zkdata";
		try
		{
			List<ZKData> list = dataService.selectZKData(record, page);
			request.setAttribute("list", list);
			request.setAttribute("pagePara",page);
			request.setAttribute("tongyicode", record.getTongyicode());
			request.setAttribute("caijishijian", record.getCaijishijian());
			request.setAttribute("caijishijianend", record.getCaijishijianend());
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 检索大宇三参数表中数据
	 * @param request
	 * @param record
	 * @param page
	 * @return
	 */
	@RequestMapping("/selectWtldData")
	public String selectWtldData(HttpServletRequest request,WtldData record,PagePara page)
	{
		String result = "WEB-INF/jsp/shuizhi/wtlddata";
		try
		{
			List<WtldData> list = dataService.selectWtldData(record, page);
			request.setAttribute("list", list);
			request.setAttribute("pagePara",page);
			request.setAttribute("disijiid", record.getDisijiid());
			request.setAttribute("caijishijian", record.getCaijishijian());
			request.setAttribute("caijishijianend", record.getCaijishijianend());
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 检索大宇七参数表中数据
	 * @param request
	 * @param record
	 * @param page
	 * @return
	 */
	@RequestMapping("/selectWtldSzyData")
	public String selectWtldSzyData(HttpServletRequest request,WtldSzyData record,PagePara page)
	{
		String result = "WEB-INF/jsp/shuizhi/wtldszydata";
		try
		{
			List<WtldSzyData> list = dataService.selectWtldSzyData(record, page);
			request.setAttribute("list", list);
			request.setAttribute("pagePara",page);
			request.setAttribute("shebeiid", record.getShebeiid());
			request.setAttribute("caijishijian", record.getCaijishijian());
			request.setAttribute("caijishijianend", record.getCaijishijianend());
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 检索tf_common_Data表中数据
	 * @param request
	 * @param record
	 * @param page
	 * @return
	 */
	@RequestMapping("/selectDataCommon")
	public String selectDataCommon(HttpServletRequest request,Data record,PagePara page)
	{
		String result = "WEB-INF/jsp/data/list";
		try
		{
			List<Data> list = dataService.selectCommon(record, page);
			request.setAttribute("list", list);
			request.setAttribute("pagePara",page);
			request.setAttribute("flag", (String)(request.getParameter("flag")));
			request.setAttribute("stationnumber", record.getStationnumber());
			request.setAttribute("datetime", record.getDatetime());
			request.setAttribute("datetimeend", record.getDatetimeend());
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 水位曲线图
	 * **/
	@RequestMapping("/selectDataLine")
	public String selectDataLine(HttpServletRequest request,Data record)
	{
		String result = "WEB-INF/jsp/data/view";
		try
		{
			String fac=request.getParameter("factory");
			int factory=0;
			if(fac!=null&&fac!=""){
				factory=Integer.parseInt(fac);
			}
			Map<String,String> list = dataService.selectLine(record,factory);
			Rtu rtu = dataService.selectEqui(record,factory);
			request.setAttribute("datal", list);
			request.setAttribute("rtuu",rtu);	
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 中科水质曲线图
	 * **/
	@RequestMapping("/selectZKDataLine")
	public String selectZKDataLine(HttpServletRequest request,ZKData record)
	{
		String result = "WEB-INF/jsp/shuizhi/zkdataview";
		try
		{
			Map<String,String> list = dataService.selectZKLine(record);
			ZKRtu rt=new ZKRtu();
			rt.setTongyicode(record.getTongyicode());
			List<ZKRtu> rtus = equiService.selectZKRtu(rt, null, null);			
			if(rtus != null)
			{
				ZKRtu rtu=rtus.get(0);
				request.setAttribute("rtuu", rtu);
			}
			request.setAttribute("datal", list);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 大宇三参数水质曲线图
	 * **/
	@RequestMapping("/selectWtldDataLine")
	public String selectWtldDataLine(HttpServletRequest request,WtldData record)
	{
		String result = "WEB-INF/jsp/shuizhi/wtlddataview";
		try
		{
			Map<String,String> list = dataService.selectWtldLine(record);
			WtldRtu rt=new WtldRtu();
			rt.setId(Integer.parseInt(record.getDisijiid()));
			List<WtldRtu> rtus = equiService.selectWtldRtu(rt, null, null);			
			if(rtus != null&&rtus.size()>0)
			{
				WtldRtu rtu=rtus.get(0);
				request.setAttribute("rtuu", rtu);
			}
			request.setAttribute("datal", list);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 大宇七参数水质曲线图
	 * **/
	@RequestMapping("/selectWtldSzyDataLine")
	public String selectWtldSzyDataLine(HttpServletRequest request,WtldSzyData record)
	{
		String result = "WEB-INF/jsp/shuizhi/wszydataview";
		try
		{
			Map<String,String> list = dataService.selectWtldSzyLine(record);
			WtldSzyRtu rt=new WtldSzyRtu();
			rt.setId(record.getShebeiid());
			List<WtldSzyRtu> rtus = equiService.selectWtldSzyRtu(rt, null, null);			
			if(rtus != null)
			{
				WtldSzyRtu rtu=rtus.get(0);
				request.setAttribute("rtuu", rtu);
			}
			request.setAttribute("datal", list);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return result;
	}
	
	@RequestMapping("/selectExport")
	public void selectExport(HttpServletResponse response,HttpServletRequest request,Data record,ZKData zk,WtldData wtld,WtldSzyData szy)
	{
		String fac=request.getParameter("factory");
		int factory=0;
		if(fac!=null){
			factory=Integer.parseInt(fac);
		}
		String path = request.getRealPath("/");
		path = path.replaceAll("[\\\\]+","/");
		String xmlFile =null; 
		
		List list = null;
		String flag = (String)(request.getParameter("flag"));

		if(flag != null && flag.trim().equals("1"))
		{
			xmlFile=path + "config/export_data.xml";
			list = dataService.exportRtu(record,null);
		}else if(flag != null && flag.trim().equals("zk")){
			xmlFile=path + "config/export_zk_data.xml";
			list = dataService.selectZKData(zk, null);
			
		}else if(flag != null && flag.trim().equals("wtld")){
			xmlFile=path + "config/export_wtld_data.xml";
			list = dataService.selectWtldData(wtld, null);
			
		}else if(flag != null && flag.trim().equals("wtldszy")){
			xmlFile=path + "config/export_wtldszy_data.xml";
			list = dataService.selectWtldSzyData(szy, null);
	
		}else{
			xmlFile=path + "config/export_data.xml";
			list = dataService.exportCommon(record,null,factory);
		}
		XmlConfig config = null;
		ParseXmlFile parse = new ParseXmlFile();
		config = parse.parseXml(xmlFile);
		CreateExcelPoi poi = new CreateExcelPoi();
		poi.setFileName("sheet1");
		String[] columnName = config.getColumnName();
		String[] filedName = config.getFieldName();		
		int[] refindex = config.getRefindex();
		String[] refcon = config.getRefcon();
		String[] type = config.getCellType();
		String replace = null;//"#sex:0,1;1,2;#";
		poi.setColumnName(columnName);
		poi.setFiledName(filedName);
		poi.setRefcon(refcon);
		poi.setRefindex(refindex);
		poi.setReplace(replace);	
		poi.setCellType(type);
		poi.setFileSavePath(path+"temp/");
		
		
		poi.setList(list);
		poi.setCls(Data.class);	
		String name=null;
		try
		{
			if(flag != null && flag.trim().equals("zk")){
				ZKRtu zk1=new ZKRtu();
				zk1.setShebeicode(zk.getTongyicode());
				List<ZKRtu> rtu=equiService.selectZKRtu(zk1, null, null);
				name = rtu.get(0).getQuyu();

			}else if(flag != null && flag.trim().equals("wtld")){
				WtldRtu wtld1=new WtldRtu();
				wtld1.setShebeicode(wtld.getDisijiid());
				List<WtldRtu> rtu=equiService.selectWtldRtu(wtld1, null, null);
				name = rtu.get(0).getHaopai();
				
			}else if(flag != null && flag.trim().equals("wtldszy")){
				WtldSzyRtu wszy1=new WtldSzyRtu();
				wszy1.setId(szy.getShebeiid());
				List<WtldSzyRtu> rtu=equiService.selectWtldSzyRtu(wszy1, null, null);
			    name = rtu.get(0).getMingcheng();
		
			}else{
				Rtu rtu = dataService.selectEqui(record,factory);
				name = rtu.getStationname();
			}
			
			
			if(StringUtils.isBlank(name))
			{
				name = record.getStationnumber();
			}
			response.setHeader("Accept-Ranges", "bytes");
			response.setHeader("Content-disposition", "attachment; filename=" + new String(name.getBytes("GBK"), "ISO8859-1") + ".xls");
	        response.setContentType("application/octet-stream");
			InputStream stream = poi.getExcelStream(true);
			OutputStream out = response.getOutputStream();
			byte[] data = new byte[1024];
			int len = 0;
			while((len = stream.read(data)) !=-1)
			{
				out.write(data,0,len);
			}
			stream.close();
			out.flush();
			out.close();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
	}

	@RequestMapping("/toExport")
	public String toExport(HttpServletResponse response,HttpServletRequest request)
	{
		String result="WEB-INF/jsp/data/export";
		User login = (User)(request.getSession().getAttribute(Configure.LOGIN_USER));
//		检索地区列表
		List<Area> areaList = equiService.selectArea(login.getUcode().trim());
		request.setAttribute("areaList", areaList);
		return result;
	}
	/**
	 * 导出所有数据
	 * @param response
	 * @param request
	 * @param record
	 */
	@RequestMapping("/selectDataExport")
	public void selectDataExport(HttpServletResponse response,HttpServletRequest request,Data record)
	{
		
		record.setStationnumber(request.getParameter("areaCode"));
		String path = request.getRealPath("/");
		path = path.replaceAll("[\\\\]+","/");
		String xmlFile = path + "config/export_all_data.xml";
		XmlConfig config = null;
		ParseXmlFile parse = new ParseXmlFile();
		config = parse.parseXml(xmlFile);
		CreateExcelPoi poi = new CreateExcelPoi();
		poi.setFileName("sheet1");
		String[] columnName = config.getColumnName();
		String[] filedName = config.getFieldName();	
		int[] refindex = config.getRefindex();
		String[] refcon = config.getRefcon();
		String[] type = config.getCellType();
		String replace = null;//"#sex:0,1;1,2;#";
		poi.setColumnName(columnName);
		poi.setFiledName(filedName);
		poi.setRefcon(refcon);
		poi.setRefindex(refindex);
		poi.setReplace(replace);	
		poi.setCellType(type);
		poi.setFileSavePath(path+"temp/");
		List<Data> list = null;
		String flag = (String)(request.getParameter("flag"));
		list = dataService.selectExportData(record);
		poi.setList(list);
		poi.setCls(Data.class);
		Date date=new Date();
		try
		{
			String str ="";
			if(record.getDatetime()!=null){
			str = new java.text.SimpleDateFormat("yyyy年数据备份").format(record.getDatetime());
			}else{
				str = new java.text.SimpleDateFormat("yyyy年数据备份").format(date.getTime());	
			}
			response.setHeader("Accept-Ranges", "bytes");
			response.setHeader("Content-disposition", "attachment; filename=" + new String(str.getBytes("GBK"), "ISO8859-1") + ".xls");
	        response.setContentType("application/octet-stream");
			InputStream stream = poi.getExcelStream(true);
			OutputStream out = response.getOutputStream();
			byte[] data = new byte[1024];
			int len = 0;
			while((len = stream.read(data)) !=-1)
			{
				out.write(data,0,len);
			}
			stream.close();
			out.flush();
			out.close();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
	}
}
